package com.hemaapp.yjnh.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.view.View.OnClickListener;

import com.hemaapp.hm_FrameWork.HemaNetTask;
import com.hemaapp.hm_FrameWork.dialog.HemaButtonDialog;
import com.hemaapp.hm_FrameWork.result.HemaBaseResult;
import com.hemaapp.hm_FrameWork.result.HemaPageArrayResult;
import com.hemaapp.hm_FrameWork.view.RefreshLoadmoreLayout;
import com.hemaapp.yjnh.BaseApplication;
import com.hemaapp.yjnh.BaseHttpInformation;
import com.hemaapp.yjnh.R;
import com.hemaapp.yjnh.ViewPagerFragment;
import com.hemaapp.yjnh.activity.BuyerOrderDetailActivity;
import com.hemaapp.yjnh.activity.BuyerCustomOrderDetailActivity;
import com.hemaapp.yjnh.activity.FriendPayActivity;
import com.hemaapp.yjnh.activity.FriendPayDetailActivity;
import com.hemaapp.yjnh.activity.PayActivity;
import com.hemaapp.yjnh.adapter.OrderListAdapter;
import com.hemaapp.yjnh.adapter.RecyclerTenDecoration;
import com.hemaapp.yjnh.listener.OrderItemClickListener;
import com.hemaapp.yjnh.bean.EventBusConfig;
import com.hemaapp.yjnh.bean.EventBusMsg;
import com.hemaapp.yjnh.bean.Order;
import com.hemaapp.yjnh.bean.Order.BillChild;
import com.hemaapp.yjnh.bean.User;
import com.hemaapp.yjnh.view.DeliveryDialog;

import java.util.ArrayList;

import de.greenrobot.event.EventBus;
import de.greenrobot.event.Subscribe;
import xtom.frame.util.XtomToastUtil;
import xtom.frame.view.XtomRefreshLoadmoreLayout;

/**
 * 用户端的商品订单列表
 * @author GuiyouZhang
 */
public class OrderListFragment extends ViewPagerFragment implements OrderItemClickListener{

    private RefreshLoadmoreLayout parentLayout;
    private RecyclerView recyclerView;

    private User user;
    private int page = 0;
    private OrderListAdapter adapter;
    private ArrayList<Order> orders = new ArrayList<>();
    private String billtype = "1";//订单类型	1:普通订单；2:定制订单；3:预约订单；4代付订单
    private String keytype;//订单的类型：	1:全部；2:待支付；3:待发货；4:待收货；5:待评价；6:待确认

    @Override
    public void onCreate(Bundle savedInstanceState) {
        setContentView(R.layout.fragment_viewpager_refresh_recycler);
        user = BaseApplication.getInstance().getUser();
        super.onCreate(savedInstanceState);
        EventBus.getDefault().register(this);
        if (savedInstanceState != null) {
            keytype = savedInstanceState.getString("keytype");
        }
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        outState.putString("keytype", keytype);
        super.onSaveInstanceState(outState);
    }

    @Override
    public void onDestroy() {
        EventBus.getDefault().unregister(this);
        super.onDestroy();
    }

    public void setBilltype(String billtype) {
        this.billtype = billtype;
    }

    public void setKeytype(String keytype) {
        this.keytype = keytype;
    }

    private void getOrders() {
        if (user != null)
            getNetWorker().orderList(user.getToken(), billtype, keytype, page + "");
    }

    @Override
    protected void callBeforeDataBack(HemaNetTask netTask) {
        BaseHttpInformation information = (BaseHttpInformation) netTask
                .getHttpInformation();
        switch (information) {
            case ORDER_SAVEOPERATE:
            case ORDER_LIST:
                showProgressDialog("请稍候");
                break;
        }
    }

    @Override
    protected void callAfterDataBack(HemaNetTask netTask) {
        BaseHttpInformation information = (BaseHttpInformation) netTask
                .getHttpInformation();
        switch (information) {
            case ORDER_SAVEOPERATE:
            case ORDER_LIST:
                if (!isHidden())
                    cancelProgressDialog();
                break;
        }
    }

    @Override
    protected void callBackForServerSuccess(HemaNetTask netTask,
                                            HemaBaseResult baseResult) {
        BaseHttpInformation information = (BaseHttpInformation) netTask
                .getHttpInformation();
        switch (information) {
            case ORDER_SAVEOPERATE:
                String keytype = netTask.getParams().get("keytype");
                if (keytype.equals("1")) {
                    XtomToastUtil.showShortToast(getActivity(), "取消订单成功!");
                }else if (keytype.equals("2")) {
                    XtomToastUtil.showShortToast(getActivity(), "确认收货成功!");
                }else if (keytype.equals("7")) {
                    XtomToastUtil.showShortToast(getActivity(), "等待朋友代付");
                }else if ("14".equals(keytype)) {//同意帮朋友代付
                    XtomToastUtil.showShortToast(getActivity(), "代付成功");
                }else if ("15".equals(keytype)) {
                    XtomToastUtil.showShortToast(getActivity(), "拒绝代付成功");
                }
                EventBusMsg msg = new EventBusMsg();
                msg.setType(EventBusConfig.UPDATE_ORDER);
                EventBus.getDefault().post(msg);
                break;
            case ORDER_LIST:
                String page = netTask.getParams().get("page");
                HemaPageArrayResult<Order> iResult = (HemaPageArrayResult<Order>) baseResult;
                if (iResult == null || iResult.getObjects() == null)
                    return;
                if ("0".equals(page)) {// 刷新
                    parentLayout.refreshSuccess();
                    if (iResult.getObjects().size() == 0)
                        parentLayout.setLoadmoreable(false);
                    else
                        parentLayout.setLoadmoreable(true);
                    orders.clear();
                    orders.addAll(iResult.getObjects());
                } else {// 更多
                    parentLayout.loadmoreSuccess();
                    orders.addAll(iResult.getObjects());
                    if (iResult.getObjects().size() > 0) {
                        orders.addAll(iResult.getObjects());
                    } else {
                        parentLayout.setLoadmoreable(false);
                        XtomToastUtil.showShortToast(getActivity(), "已经到最后啦");
                    }
                }
                refreshData();
                break;
        }
    }

    @Override
    protected void callBackForServerFailed(HemaNetTask netTask,
                                           HemaBaseResult baseResult) {
        BaseHttpInformation information = (BaseHttpInformation) netTask
                .getHttpInformation();
        switch (information) {
            case ORDER_SAVEOPERATE:
                String keytype = netTask.getParams().get("keytype");
                if (keytype.equals("1")) {
                    XtomToastUtil.showShortToast(getActivity(), "取消订单失败,"+baseResult.getMsg());
                }else if (keytype.equals("7")) {
                    XtomToastUtil.showShortToast(getActivity(), "代付失败,"+baseResult.getMsg());
                }else
                    XtomToastUtil.showShortToast(getActivity(), "操作失败," + baseResult.getMsg());
                break;
            case ORDER_LIST:
                XtomToastUtil.showShortToast(getActivity(), "获取订单失败," + baseResult.getMsg());
                String page = netTask.getParams().get("page");
                if ("0".equals(page))// 刷新
                    parentLayout.refreshFailed();
                else
                    parentLayout.loadmoreFailed();
                refreshData();
                break;
        }
    }

    @Override
    protected void callBackForGetDataFailed(HemaNetTask netTask, int failedType) {
        BaseHttpInformation information = (BaseHttpInformation) netTask
                .getHttpInformation();
        switch (information) {
            case ORDER_SAVEOPERATE:
                String keytype = netTask.getParams().get("keytype");
                if (keytype.equals("1")) {
                    XtomToastUtil.showShortToast(getActivity(), "取消订单失败,请稍后再试");
                }else if (keytype.equals("7")) {
                    XtomToastUtil.showShortToast(getActivity(), "代付失败,请稍后再试");
                }else
                    XtomToastUtil.showShortToast(getActivity(), "操作失败,请稍后再试");
                break;
            case ORDER_LIST:
                XtomToastUtil.showShortToast(getActivity(), "获取订单失败,请稍后再试");
                String page = netTask.getParams().get("page");
                if ("0".equals(page))// 刷新
                    parentLayout.refreshFailed();
                else
                    parentLayout.loadmoreFailed();
                refreshData();
                break;
        }
    }

    private void refreshData() {
        if (adapter == null) {
            adapter = new OrderListAdapter(getActivity(), orders, this);
            recyclerView.setAdapter(adapter);
            recyclerView.addItemDecoration(new RecyclerTenDecoration(getActivity()));
        }else
            adapter.notifyDataSetChanged();
    }

    @Override
    protected void findView() {
        parentLayout = (RefreshLoadmoreLayout) findViewById(R.id.refreshLoadmoreLayout);
        recyclerView = (RecyclerView) findViewById(R.id.recycler_view);
    }

    @Override
    protected void setListener() {
        parentLayout.setOnStartListener(new XtomRefreshLoadmoreLayout.OnStartListener() {
            @Override
            public void onStartRefresh(XtomRefreshLoadmoreLayout v) {
                page = 0;
                getOrders();
            }

            @Override
            public void onStartLoadmore(XtomRefreshLoadmoreLayout v) {
                page++;
                getOrders();
            }
        });
        LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        recyclerView.setLayoutManager(layoutManager);
    }

    @Override
    public void onItemClickListener(int position) {
        Order order = orders.get(position);
        Intent intent = new Intent();
        //订单客户id和我的id不相同，说明是别人的代付订单，下面只去判断代付状态就可以。
        if (!order.getClient_id().equals(BaseApplication.getInstance().getUser().getId())) {//别人的订单
            intent = new Intent(getActivity(), FriendPayDetailActivity.class);
            intent.putExtra("order_id", order.getId());
            startActivity(intent);
        }else {
            //getOther_payflag:0非代付;1待确认;2接受代付;3拒绝代付
            if (order.getOther_payflag().equals("0") || order.getOther_payflag().equals("2") || order.getOther_payflag().equals("3")) {
                if (billtype.equals("1")) {
                    intent.setClass(getActivity(), BuyerOrderDetailActivity.class);
                    intent.putExtra("order_id", orders.get(position).getId());
                    startActivity(intent);
                } else if (billtype.equals("2")) {
                    intent.setClass(getActivity(), BuyerCustomOrderDetailActivity.class);
                    intent.putExtra("order_id", orders.get(position).getId());
                    startActivity(intent);
                }
            }else {
                intent = new Intent(getActivity(), FriendPayDetailActivity.class);
                intent.putExtra("order_id", order.getId());
                startActivity(intent);
            }
        }
    }

    @Override
    public void onPay(int position) {
        Intent itPay = new Intent(getActivity(), PayActivity.class);
        itPay.putExtra("order", orders.get(position));
        startActivity(itPay);
    }

    @Override
    public void onRefusePay(final int position) {
        HemaButtonDialog hbDialog = new HemaButtonDialog(getActivity());
        hbDialog.setText("确定拒绝为对方代付吗？");
        hbDialog.setLeftButtonText("取消");
        hbDialog.setRightButtonText("确定");
        hbDialog.setButtonListener(new HemaButtonDialog.OnButtonListener() {

            @Override
            public void onRightButtonClick(HemaButtonDialog dialog) {
                dialog.cancel();
                if (user != null && orders.get(position) !=null) {
                    getNetWorker().orderSaveoperate(user.getToken(), orders.get(position).getId(), "15", "无",
                            "无", "无", "无");
                }
            }

            @Override
            public void onLeftButtonClick(HemaButtonDialog dialog) {
                dialog.cancel();
            }
        });
    }

    /**朋友代付
     * @param position
     */
    @Override
    public void onPayBehalf(int position) {
        ArrayList<BillChild> items = orders.get(position).getChildren();
        String name = items.get(0).getName();
        for (int i = 1; i < items.size(); i++) {
            name = name+"\n "+items.get(i).getName();
        }
        Intent itFriend = new Intent(getActivity(), FriendPayActivity.class);
        itFriend.putExtra("name", name);
        itFriend.putExtra("fee", orders.get(position).getTotal_fee());
        itFriend.putExtra("info", user.getNickname()+"("+user.getUsername()+")");
        itFriend.putExtra("deal_here", true);
        itFriend.putExtra("order_id", orders.get(position).getId());
        startActivity(itFriend);
    }

    @Override
    public void onCancel(final int position) {
        HemaButtonDialog hbDialog = new HemaButtonDialog(getActivity());
        hbDialog.setText("确认取消订单吗？");
        hbDialog.setLeftButtonText("取消");
        hbDialog.setRightButtonText("确定");
        hbDialog.setButtonListener(new HemaButtonDialog.OnButtonListener() {

            @Override
            public void onRightButtonClick(HemaButtonDialog dialog) {
                dialog.cancel();
                if (user != null && orders.get(position) !=null) {
                    getNetWorker().orderSaveoperate(user.getToken(), orders.get(position).getId(), "1", "无",
                            "无", "无", "无");
                }
            }

            @Override
            public void onLeftButtonClick(HemaButtonDialog dialog) {
                dialog.cancel();
            }
        });
    }

    @Override
    public void onReceive(final int position) {
        HemaButtonDialog hbDialog = new HemaButtonDialog(getActivity());
        hbDialog.setText("一旦确定，交易自动完成");
        hbDialog.setLeftButtonText("取消");
        hbDialog.setRightButtonText("确定");
        hbDialog.setButtonListener(new HemaButtonDialog.OnButtonListener() {

            @Override
            public void onRightButtonClick(HemaButtonDialog dialog) {
                // TODO Auto-generated method stub
                dialog.cancel();
                if (user != null && orders.get(position) !=null) {
                    getNetWorker().orderSaveoperate(user.getToken(), orders.get(position).getId(), "2", "无",
                            "无", "无", "无");
                }
            }

            @Override
            public void onLeftButtonClick(HemaButtonDialog dialog) {
                dialog.cancel();
            }
        });
    }

    @Override
    public void onAgreeReturn(final int position) {//这里是评价商品的功能
    }

    @Override
    public void onRefuseReturn(final int position) {//这里是申请售后的功能
    }

    @Override
    public void onDeliveryGoods(final int position) {
        final DeliveryDialog deliveryDialog = new DeliveryDialog(getActivity()).builder();
        deliveryDialog.setClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                String expressName = deliveryDialog.getExpressName();
                String expressNum = deliveryDialog.getExpressNum();
                if (isNull(expressName)) {
                    XtomToastUtil.showShortToast(getActivity(), "快递公司名称不能为空!");
                    return;
                }
                if (expressNum.isEmpty()) {
                    XtomToastUtil.showShortToast(getActivity(), "快递单号不能为空!");
                    return;
                }
                if (user != null && orders.get(position) != null) {
                    getNetWorker().orderSaveoperate(user.getToken(), orders.get(position).getId(), "4", "无",
                            "无", expressName, expressNum);
                }
                deliveryDialog.dismiss();
            }
        });
        deliveryDialog.show();
    }

    @Override
    public void fetchData() {
        getOrders();
    }

    @Subscribe
    public void onEventMainThread(EventBusMsg msg) {
        if (msg.getType() == EventBusConfig.UPDATE_ORDER) {
            if (!isHidden()) {
                page = 0;
                getOrders();
            }
        }
    }
}
